package org.tinygroup.signature;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.dom.DOMSource;

import org.springframework.integration.transformer.AbstractPayloadTransformer;
import org.springframework.integration.transformer.MessageTransformationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class ObjectToDocumentTransformer extends
		AbstractPayloadTransformer<Object, Element> {

	@Override
	protected Element transformPayload(Object payload) throws Exception {
		if (payload instanceof Document) {
			return ((Document)payload).getDocumentElement();
		}else if(payload instanceof DOMSource){
			DOMSource domSource=(DOMSource)payload;
			return (Element) domSource.getNode();
		}
		InputStream inputStream;
		if (payload instanceof InputStream) {
			inputStream = (InputStream) payload;
		} else if (payload instanceof byte[]) {
			inputStream = new ByteArrayInputStream((byte[]) payload);
		} else if (payload instanceof char[]) {
			inputStream = new ByteArrayInputStream(
					new String((char[]) payload).getBytes("UTF-8"));
		} else if (payload instanceof String) {
			inputStream = new ByteArrayInputStream(
					((String) payload).getBytes("UTF-8"));
		} else {
			throw new MessageTransformationException(
					"the class of payload must be byte[],char[],String,InputStream,DOMSource");
		}
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		dbf.setNamespaceAware(true);
		return dbf.newDocumentBuilder().parse(inputStream).getDocumentElement();
	}

}
